package com.xnchat.pro.utils;

import cn.hutool.core.text.UnicodeUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpException;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

public class MyDrrrUtil {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    public void sendMessage(String sessionId, String message) {

        try {
            HttpResponse cookie = HttpRequest.post("https://drrr.com/room/?ajax=1&api=json")
                    .header("Cookie", sessionId)
                    .body("message=/me" + message).timeout(10000).execute();
            logger.info("消息状态码：" + cookie.getStatus());
        } catch (Exception e) {
            logger.warn("发送消息x请求超时 ：" + message);
        }
    }

    public String getMessage(String time, String code) {
        HttpResponse execute;
        while (true) {
            try {
                execute = HttpRequest.get("https://drrr.com/json.php?update=" + time)
                        .header("Content-Type", "application/json")
                        .header("cookie", code)
                        .header("Connection", "keep-alive").timeout(6000)
                        .execute();
                int reCode = execute.getStatus();
                //异常情况重新请求
                if (reCode != 200 && reCode != 503) {
                    System.out.println("错误代码：" + reCode);
                    continue;
                }
                if (503 == reCode) {
                    logger.error("人机验证已开启，服务自动停止");
                    return "";
                }
            } catch (HttpException e) {
                logger.debug("请求超时 time=：" + time + " error:" + e);
                continue;
            }
            break;
        }
        //处理返回结果
        String result = execute.body();
        return UnicodeUtil.toString(result);
    }

    /**
     * @param userName 小凝[robot]#P[bFv]9. %E5%B0%8F%E5%87%9D%5Brobot%5D%23P%5BbFv%5D9.
     * @param icon     kanra
     * @return
     */
    public NormalReturn xnLogon(String userName, String icon) {
        int redirectCode = 302;
        if (userName == null || icon == null) {
            userName = "aozaki[robot]";
            icon = "aozaki";
        }
        userName = URLUtil.encode(userName);
        int random = new Random().nextInt(1024);
        HttpRequest request = HttpUtil.createGet("https://drrr.com/")
                .header("User-Agent", "Bot;Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0." + random + ".66 Safari/537.36");
        //这里需要清除cookie，不然下次调用还会带着cookie
        request.cookie();
        HttpResponse logIndex = request.execute();
        //获取session
        logger.warn(logIndex.headers().toString());
        try {
            Map<String, List<String>> headers = logIndex.headers();
            if (headers.size() == 20) {
                return NormalReturn.FAIL;
            }
            String s = headers.get("Set-Cookie").get(0);
            String[] split = s.split("path=");
            String session = split[0];
            session = session.trim();
            //获取token
            String index = logIndex.body();
            int i = index.indexOf("\"token\" data-value=\"");
            i += 20;
            String token = index.substring(i, i + 32);
            String encode = "name=" + userName + "&login=ENTER&token=" + token + "&direct-join=&language=zh-CN&icon=" + icon;
            HttpResponse execute = HttpUtil.createPost("https://drrr.com").header("Cookie", session)
                    .header("User-Agent", "Bot;Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.66 Safari/537.36").body(encode).execute();
            //登录房间list
            logger.info("登录状态码 " + execute.getStatus());
            logger.info("session=" + session);
            if (redirectCode != execute.getStatus()) {
                return NormalReturn.FAIL.addMessage("登录失败").add("re", execute)
                        .add("token", token).add("session", session);
            }

            HttpRequest.get("https://drrr.com/lounge/").header("Cookie", session)
                    .execute();
            HttpResponse roomlist = HttpRequest.get("https://drrr.com/lounge?api=json").header("Cookie", session)
                    .execute();
            NormalReturn normalReturn = new NormalReturn();
            normalReturn.add("cookie", session)
                    .add("roomList", roomlist.body());

            normalReturn.setCode(NormalReturn.SUCCESS_CODE);
            return normalReturn;
        } catch (Exception e) {
            return NormalReturn.FAIL.addMessage(e.getMessage());
        }

    }

    public void normalSend(String sessionId, String message) {

        try {
            HttpResponse cookie = HttpRequest.post("https://drrr.com/room/?ajax=1&api=json")
                    .header("Cookie", sessionId)
                    .body(message).timeout(10000).execute();
            logger.info("消息状态码：" + cookie.getStatus());
            Thread.sleep(ThreadLocalRandom.current().nextInt(2000));
        } catch (Exception e) {
            logger.warn("发送消息x请求超时 ：" + message);
        }


    }

}
